package endpoint

import (
	"encoding/json"
	"errors"
	"log"
	"net/http"

	"gitee.com/daigd/v-blog-demo-go/model"
	"gitee.com/daigd/v-blog-demo-go/service"
)

// LoginHandle 处理登录接口逻辑
func LoginHandle(w http.ResponseWriter, r *http.Request) {
	var err error
	method := r.Method
	log.Println("method:", method)
	switch method {
	case "POST":
		err = handlePost(w, r)
	default:
		err = errors.New("请求错误")
	}
	vo := model.ResultVO{Code: 200, Desc: "登录成功"}
	if err != nil {
		vo.Code = 915
		vo.Desc = err.Error()
	}
	output, _ := json.MarshalIndent(&vo, "", "\t")
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	w.Write(output)

}

func handlePost(w http.ResponseWriter, r *http.Request) error {
	_ = r.ParseForm()
	userName := r.FormValue("username")
	password := r.FormValue("password")

	if len(userName) == 0 || len(password) == 0 {
		return errors.New("用户名或密码不能为空")
	}

	if service.CheckUserr(userName, password) {
		return nil
	}

	return errors.New("用户名或密码错误")
}
